package org.bonorsoft.modules.control.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.map.MapUtil;
import org.apache.shiro.SecurityUtils;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.system.vo.LoginUser;
import org.bonorsoft.modules.control.entity.CheckPhoto;
import org.bonorsoft.modules.control.entity.CheckResult;
import org.bonorsoft.modules.control.entity.House;
import org.bonorsoft.modules.control.entity.Unit;
import org.bonorsoft.modules.control.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 检查结果
 * @Author: WilliamYe
 * @Date: 2021-02-26
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/control/result")
public class CheckResultController extends BonorController<CheckResult, ICheckResultService> {
    private String prefix = "control/result";

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IUnitService unitService;

    @Autowired
    private ICheckResultService checkResultService;

    @Autowired
    private ICheckPhotoService checkPhotoService;

    /**
     * 首页
     */
    @RequiresPermissions("control:result:view")
    @GetMapping()
    public String index(String addressId, ModelMap map) {
        map.put("addressId", addressId);
        return prefix + "/result";
    }

    /**
     * 分页列表查询
     *
     * @param checkResult
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "检查结果-分页列表查询")
    @RequiresPermissions("control:result:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(CheckResult checkResult,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CheckResult> queryWrapper = QueryGenerator.initQueryWrapper(checkResult, req.getParameterMap());
        Page<CheckResult> page = new Page<CheckResult>(pageNo, pageSize);
        IPage<CheckResult> pageList = checkResultService.page(page, queryWrapper);

        Set<String> conditionsSet = new HashSet<>();
        pageList.getRecords().forEach(item -> {
            String[] split = item.getConditions().split("/");
            conditionsSet.addAll(Arrays.asList(split));
        });

        return Result.ok(MapUtil.builder()
                .put("list", pageList)
                .put("conditions", conditionsSet)
                .build());
    }

    /**
     * 添加页面
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 添加
     *
     * @param checkResult
     * @return
     */
    @AutoLog(value = "检查结果-添加")
    @RequiresPermissions("control:result:add")
    @PostMapping(value = "/add")
    @ResponseBody
    public Result<?> add(@Validated CheckResult checkResult) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        checkResult.setCheckPeople(user.getRealname());
        checkResult.setCheckTime(new Date());
        String addressId = checkResult.getAddressId();
        //判断是否存在实有房屋
        int house_count = houseService.count(new QueryWrapper<House>().eq("dzbm", addressId));
        //如果不存在房屋则继续执行
        int unit_count = 0;
        if (house_count == 0) {
            //判断是否存在实有单位
            unit_count = unitService.count(new QueryWrapper<Unit>().eq("dwdz_dzbm", addressId));
            if (unit_count > 0) { //检查结果为单位时
                Unit unit = unitService.getOne(new QueryWrapper<Unit>().eq("dwdz_dzbm", addressId));
                checkResult.setHylbdm(unit.getHylbdm());
                if (unit.getSfdqjc().equals("Y")) {
                    Integer jczq = unitService.getOne(new QueryWrapper<Unit>().eq("dwdz_dzbm", addressId)).getJczq();
                    Date checkTime = checkResult.getCheckTime();
                    Calendar nextCheckTime = new GregorianCalendar();
                    nextCheckTime.setTime(checkTime);
                    nextCheckTime.add(GregorianCalendar.DAY_OF_MONTH, jczq);
                    checkResult.setNextCheckTime(nextCheckTime.getTime());
                }
            }
        }
        if (house_count > 0) { //检查结果为房屋时
            if (houseService.getOne(new QueryWrapper<House>().eq("dzbm", addressId)).getSfdqjc().equals("Y")) {
                Integer jczq = houseService.getOne(new QueryWrapper<House>().eq("dzbm", addressId)).getJczq();
                Date checkTime = checkResult.getCheckTime();
                Calendar nextCheckTime = new GregorianCalendar();
                nextCheckTime.setTime(checkTime);
                nextCheckTime.add(GregorianCalendar.DAY_OF_MONTH, jczq);
                checkResult.setNextCheckTime(nextCheckTime.getTime());
            }
        }

        checkResultService.save(checkResult);
        return Result.ok("添加成功！");
    }

    @GetMapping("/detail/{id}")
    public String check(@PathVariable("id") String id, ModelMap map) {
        map.put("id", id);
        return prefix + "/detail";
    }

    @GetMapping("/isResult/{id}")
    @ResponseBody
    public Integer isResult(@PathVariable("id") String id) {
        return checkResultService.count(new QueryWrapper<CheckResult>().eq("address_id", id));
    }

    /**
     * @param id 模板id^基础地址id
     * @return
     */
    @GetMapping("/getResult/{id}")
    @ResponseBody
    public Map getResult(@PathVariable("id") String id) {
        CheckResult checkResult = checkResultService.getById(id);
        List<CheckPhoto> photoList = checkPhotoService.list(new QueryWrapper<CheckPhoto>().eq("dzbm", checkResult.getAddressId()));
//        System.out.println(photoList);
        return MapUtil.builder().put("checkResult", checkResult).put("photo", photoList).build();
    }

    /**
     * 编辑页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("editInfo", checkResultService.getById(id));
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param checkResult
     * @return
     */
    @AutoLog(value = "检查结果-编辑")
    @RequiresPermissions("control:result:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated CheckResult checkResult) {
        checkResultService.updateById(checkResult);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "检查结果-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        checkResultService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "检查结果-批量删除")
    @RequiresPermissions("control:result:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.checkResultService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "检查结果-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CheckResult checkResult = checkResultService.getById(id);
        return Result.ok(checkResult);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param checkResult
     */
    @AutoLog(value = "检查结果-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CheckResult checkResult) {
        return super.exportXls(request, checkResult, CheckResult.class, "检查结果");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "检查结果-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CheckResult.class);
    }

    /**
     * 模板下载
     *
     * @return
     */
    @AutoLog(value = "检查结果-模板下载", operateType = 6)
    @RequestMapping(value = "/importTemplate")
    public ModelAndView importTemplate() {
        return super.importTemplateXls(CheckResult.class, "检查结果");
    }


    @PostMapping("/addOpinion")
    @ResponseBody
    public Result<?> addOpinion(CheckResult result) {
        checkResultService.updateById(result);
        return Result.ok("操作成功！");
    }
}
